package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-system/model/cache"
	"video-system/model/mysql"

	"video-system/userrpc/internal/svc"
	"video-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册一体化
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.UserInfo{
		PhoneNum:   in.PhoneNum,
		Pwd:        in.Pwd,
		NickName:   fmt.Sprintf("用户_%d", rand.Intn(100000)),
		AvatarLink: "https://www.baidu",
	}

	if err := user.FindFirstOrCreate(mysql.DB, in.PhoneNum); err != nil {
		return nil, err
	}

	if in.LoginType == 1 {
		result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.PhoneNum).Result()

		if result != in.SmsCode {
			return nil, errors.New("验证码错误,请重新输入")
		}

	} else if in.LoginType == 2 {
		if user.Pwd != in.Pwd {
			return nil, errors.New("密码不正确,请重新输入")
		}
	} else {
		return nil, errors.New("请选择正确的登录方式")
	}

	if in.AccountStatus == 1 {
		return nil, errors.New("账号已禁用,请联系管理员")
	}

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
